﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using HMS.Data;
using HMS.ClassLibrary;
using System.Threading;

namespace HMS
{
    /// <summary>
    /// Interaction logic for UserWindow.xaml
    /// </summary>
    public partial class UserWindow : Window
    {
        private HMSEntities HMSContext;
        private ProgressWindow ProgressWindow;
        FormAction FormAction;

        public UserWindow()
        {
            InitializeComponent();
            HMSContext = new HMSEntities();
            InitializeControlState();
            CurrentFormAction = FormAction.View;
        }
        //triggesr updateControlState() when form action changes
        public FormAction CurrentFormAction
        {
            set
            {
                FormAction = value;
                UpdateContolState();
            }
            get { return FormAction; }

        }
        private void InitializeControlState()
        {
            ReferenceAutocompleteTextBox.ItemsSource = HMSContext.Users;
            UserTypeComboBox.ItemsSource = HMSContext.UserTypes;
        }

        private void ResetControlValues()
        {
            ReferenceAutocompleteTextBox.ItemsSource = null;

        }
        private void UpdateContolState()
        {
            switch (this.CurrentFormAction)
            {
                case FormAction.View:
                    ReferenceAutocompleteTextBox.ItemsSource = HMSContext.Users;
                    ReferenceAutocompleteTextBox.IsEnabled = true;

                    //set button states
                    SaveButton.IsEnabled = false;
                    NewButton.IsEnabled = true;
                    CancelButton.IsEnabled = true;
                    break;


                case FormAction.New:
                    ResetControlValues();
                    InitializeControlState();

                    ReferenceAutocompleteTextBox.ItemsSource = null;
                    ReferenceAutocompleteTextBox.IsEnabled = false;

                    //set button states
                    SaveButton.IsEnabled = true;
                    NewButton.IsEnabled = false;
                    CancelButton.IsEnabled = true;
                    break;
            }

        }
        private bool ValidateControlValues()
        {

            if (String.IsNullOrEmpty( UserNameTextBox.Text.Trim()))
            {
                MessageBox.Show(Properties.Resources.UserNameNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
            if (UserNameTextBox.Text.Trim().Length < 4 || UserNameTextBox.Text.Trim().Length >8)
            {
                MessageBox.Show(Properties.Resources.UserNameLengthInvalid, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
            if (String.IsNullOrEmpty(PasswordTextBox.Password.Trim()))
            {
                MessageBox.Show(Properties.Resources.PasswordNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
            if (PasswordTextBox.Password.Trim().Length < 4 || PasswordTextBox.Password.Trim().Length > 8)
            {
                MessageBox.Show(Properties.Resources.PasswordLengthInvalid, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
            if (UserTypeComboBox.SelectedIndex==-1)
            {
                MessageBox.Show(Properties.Resources.UserTypeNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }

            return true;
        }
        private void DisplayDetails(User user)
        {
            try
            {
                ReferenceAutocompleteTextBox.SelectedItem = user;
                UserNameTextBox.Text = user.UserName;
                PasswordTextBox.Password = user.Password;
                UserTypeComboBox.SelectedItem = user.UserType;
                IsUserActiveCheckBox.IsChecked = user.IsActive;
            }
            catch (Exception)
            {

                throw;
            }

        }
        private void Save()
        {
            try
            {
                if (ValidateControlValues())
                {
                    string userName = UserNameTextBox.Text.Trim();
                    string password = PasswordTextBox.Password;
                    string reference = HMSContext.NextSystemNumber(5).First();
                    bool isActive = true;
                    UserType userType = UserTypeComboBox.SelectedItem as UserType;
                    //encrypt the password
                    Cryptography cryptograph=new Cryptography();
                    string encryptedPassword = cryptograph.Encrypt(password);


                    User user = new User();
                    user.UserName = userName;
                    user.Password = encryptedPassword;
                    user.IsActive = isActive;
                    user.Reference = reference;
                    user.UserType = userType;

                    HMSContext.AddToUsers(user);
                    int? affectedRowCount = HMSContext.SaveChanges();
                    if (affectedRowCount != null && affectedRowCount > 0)
                    {
                        ResetControlValues();
                        //set the form action to view mode and display the saved channeling details
                        this.CurrentFormAction = FormAction.View;
                        this.DisplayDetails(user);
                        MessageBox.Show(Properties.Resources.SaveSuccessful, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);

                    }
                    else
                    {
                        MessageBox.Show(Properties.Resources.UnknownError, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);

            }
        }
        private void SaveBackgroundWorker(object sender, DoWorkEventArgs e)
        {
            try
            {
                //dispathcher needs to access ui control without having exceptions
                this.Dispatcher.Invoke((Action)(() =>
                {
                    this.Save();
                }));

            }
            catch (Exception)
            {
                throw;
            }
        }
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //show the busy indicator of saving
                ProgressWindow = new ProgressWindow(this.SaveBackgroundWorker);
                ProgressWindow.Owner = this;
                ProgressWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }
        private void NewButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.CurrentFormAction = FormAction.New;
                SystemNumber nextSystemNumber = HMSContext.SystemNumbers.Where(s => s.SystemNumberID == 5).First();
                ReferenceAutocompleteTextBox.Text = nextSystemNumber.Prefix + nextSystemNumber.NextNumber;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void ReferenceAutocompleteTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ReferenceAutocompleteTextBox.SelectedItem != null)
                {
                    User selectedUser = ReferenceAutocompleteTextBox.SelectedItem as User;
                    this.DisplayDetails(selectedUser);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
